package com.enqualcomm.kids.activities;


import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.Constants;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.manager.Controller;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.view.dialog.AddDeviceDialog;
import com.enqualcomm.kids.view.dialog.AddDeviceDialogCallBack;
import com.enqualcomm.kids.view.dialog.CommitDialogCallBack;
import com.enqualcomm.kids.view.dialog.MyPromptDialog;
import com.enqualcomm.kids.view.dialog.QRcodeDescDialog;
import com.google.zxing.Result;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.IOException;

import common.utils.DensityUtil;
import common.utils.PlatformUtil;
import common.utils.PromptUtil;
import common.zxing.ICaptureActivity;
import common.zxing.camera.CameraManager;
import common.zxing.decode.DecodeThread;
import common.zxing.utils.BeepManager;
import common.zxing.utils.CaptureActivityHandler;

@EActivity(R.layout.activity_add_watch_cid)
public class AddWatchCidActivity extends BaseActivity implements ICaptureActivity, SurfaceHolder.Callback {


    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private boolean isHasSurface;
    private Rect mCropRect;
    //    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;

    @ViewById(R.id.capture_preview)
    SurfaceView scanPreview;
    @ViewById(R.id.capture_crop_view)
    View scanCropView;
    @ViewById(R.id.capture_scan_line)
    ImageView scanLine;
    private ObjectAnimator animator;
    private int dp25;
    @ViewById(R.id.add_by_cid_btn)
    Button add_by_cid_btn;
    NetworkModel networkModel = new NetworkModel();

    @AfterViews
    void setupViews() {
        TextView title_bar_name = (TextView) findViewById(R.id.title_bar_title_tv);
        title_bar_name.setText(getString(R.string.scan_qrcode));
        TextView title_bar_terminal_name_tv = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
        View title_bar_terminal_icon_iv = findViewById(R.id.title_bar_terminal_icon_iv);
        title_bar_terminal_icon_iv.setVisibility(View.GONE);
        title_bar_terminal_name_tv.setVisibility(View.VISIBLE);
        title_bar_terminal_name_tv.setText(getString(R.string.scan_qrcode));

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        dp25 = DensityUtil.dip2px(this, 25);

        add_by_cid_btn.setText(getString(R.string.scan_input_cid));
    }

    @Click({R.id.title_bar_left_iv, R.id.lookup_tv})
    public void finishActivity() {
        finish();
    }

    @Click(R.id.where_qrcode_is_view)
    void showQrcodeDialog() {
        new QRcodeDescDialog(this).show();
    }

    @Click(R.id.add_by_cid_btn)
    void addByCid() {
        //输入cid添加手表
        stopScan();
        new AddDeviceDialog(this, false, new AddDeviceDialogCallBack() {

            @Override
            public void ok(String cid) {
                getConfig(cid);
            }

            @Override
            public void cancel() {
                startScan();
            }
        }).show();
    }

    private void getConfig(final String cid) {
//        networkModel.loadDataFromServer(new SocketRequest<AllTerminalConfig>(new GetAllTerminalConfig(cid), new NetworkListener<AllTerminalConfig>() {
//            @Override
//            public void onError(VolleyError error) {
//            }
//
//            @Override
//            public void onSuccess(AllTerminalConfig response) {
//                if (response.code==0) {
//                    Controller.getInstance().reset(response.result);
//                    Intent intent = new Intent(getApplicationContext(),FillWatchInfoActivity_.class);
//                    intent.putExtra("imei",cid);
//                    startActivity(intent);
//                    finish();
//                }else {
//                    PromptUtil.toast(getApplicationContext(),R.string.cid_invalied);
//                    startScan();
//                }
//            }
//        }));

        Controller.getInstance().setCidMode(cid);
        Intent intent = new Intent(getApplicationContext(), FillWatchInfoActivity_.class);
        intent.putExtra("imei", cid);
        startActivity(intent);
        finish();
    }

    boolean started;

    public void stopScan() {
        if (started) {
            started = false;
            if (handler != null) {
                handler.quitSynchronously();
                handler = null;
            }
//        inactivityTimer.onPause();
            beepManager.close();
            cameraManager.closeDriver();
            if (!isHasSurface) {
                scanPreview.getHolder().removeCallback(this);
            }

            animator.cancel();
        }
    }


    public void startScan() {
        if (!started) {
            started = true;
            cameraManager = new CameraManager(getApplication());
            handler = null;
            if (isHasSurface) {
                initCamera(scanPreview.getHolder());
            } else {
                scanPreview.getHolder().addCallback(this);
            }
//        inactivityTimer.onResume();

            animator = ObjectAnimator.ofFloat(scanLine, "translationY", dp25, dp25 * 7, dp25);
            animator.setDuration(4000);
            animator.setRepeatCount(-1);
            animator.start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startScan();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopScan();
    }

    @Override
    protected void onDestroy() {
        networkModel.onStop();
        super.onDestroy();
//        inactivityTimer.shutdown();
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public Rect getCropRect() {
        return mCropRect;
    }

    @Override
    public void handleDecode(Result rawResult, Bundle bundle) {
//        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        String cid = rawResult.getText();
        if (!cid.matches(Constants.CID_REGEX)) {
            PromptUtil.toast(this, R.string.cid_format_error);
        } else {
            stopScan();
            getConfig(cid);
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }

            initCrop();
        } catch (IOException ioe) {
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            displayFrameworkBugMessageAndExit();
        }

    }

    private void displayFrameworkBugMessageAndExit() {
        if (animator != null) {
            animator.cancel();
        }
        new MyPromptDialog(this, getString(R.string.cid_open_camera_error_title), getString(R.string.cid_open_camera_error_content_1) + getString(R.string.app_name)
                + getString(R.string.cid_open_camera_error_content_2), new CommitDialogCallBack() {

            @Override
            public void onCommit() {
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int dp200 = DensityUtil.dip2px(this, 200);
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);
        int top = location[1] - PlatformUtil.statusBarHeight(this);
        int left = (new AppDefault().getWindowWidth() - dp200) / 2;
        mCropRect = new Rect(left, top, dp200 + left, dp200 + top);
    }

}
